package com.yayako.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yayako.result.Result;
import com.yayako.result.ResultFactory;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthFailureHandler implements AuthenticationFailureHandler {
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest req, HttpServletResponse resp, AuthenticationException e)
      throws IOException {
    resp.setContentType("application/json;charset=utf-8");
    Result res;

    if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
      res = ResultFactory.bulidFailResult("账户名或者密码输入错误!");
    } else if (e instanceof LockedException) {
      res = ResultFactory.bulidFailResult("账户被锁定，请联系管理员!");
    } else if (e instanceof CredentialsExpiredException) {
      res = ResultFactory.bulidFailResult("密码过期，请联系管理员!");
    } else if (e instanceof AccountExpiredException) {
      res = ResultFactory.bulidFailResult("账户过期，请联系管理员!");
    } else if (e instanceof DisabledException) {
      res = ResultFactory.bulidFailResult("账户被禁用，请联系管理员!");
    } else {
      res = ResultFactory.bulidFailResult("登录失败!");
    }
    res.setCode(401);

    ObjectMapper om = new ObjectMapper();
    PrintWriter out = resp.getWriter();
    out.write(om.writeValueAsString(res));
    out.flush();
    out.close();
  }
}
